package com.GainLoop;

import java.net.ResponseCache;
import java.util.ArrayList;

import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONException;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;

import com.GainLoop.R;
import com.GainLoop.Api.ApiResponseArray;
import com.GainLoop.Api.ApiResponseObject;
import com.GainLoop.Api.Categories;
import com.GainLoop.Api.Gains;
import com.GainLoop.Api.Tags;
import com.GainLoop.Api.Entity.Category;
import com.GainLoop.Api.Entity.Gain;
import com.GainLoop.Api.Entity.Tag;
import com.GainLoop.Api.Entity.Gain.STATUS;
import com.GainLoop.Api.Entity.User;
import com.GainLoop.Data.Registry;


public class AddRequest extends Activity {
	
	
	static final int MIN_DESC_LENGTH = 5 ;
	private static final String[] TAGS = /*new String[]*/{"cool","work","israel"}; //TODO : remove in future-Meir
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addrequest);
        
        Categories categories = new Categories();
        ApiResponseArray<Category> resp = null;
        try {
			resp = categories.getAll();
		} catch (JSONException e1) {
			e1.printStackTrace();//TODO - remove in future...
		} catch (JSONRPCException e1) {
			e1.printStackTrace();//TODO - remove in future...
		}
		ArrayList<Category> allCategories = null;
		if(resp==null){
			declareInternalError();
			Log.v("Categories resp=","null");
			return;//TODO : maybe change this ? - Meir
		}
		allCategories = resp.getData();//TODO : something does not work well... need to check it.. - Meir
		
		String[] allCategoriesStrArr;
		
		Log.v("is allCategories null?=",Boolean.toString(allCategories==null));
		Log.v("return code=",Integer.toString(resp.getReturnCode()));
		
		if(allCategories==null){
			declareInternalError();
			Log.v("Categories fetch","Failed");
			return;
		}
		else{
			Log.v("allCategories size=",Integer.toString(allCategories.size()));
			allCategoriesStrArr = transformToStringArray(allCategories);
		}
        
        //adding spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, allCategoriesStrArr);   
        Spinner spinner = (Spinner) findViewById(R.id.category_spinner);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        
        //adding description start
        User user=Registry.GetUser();
        TextView gainDescStart = (TextView) findViewById(R.id.add_gain_description_start);
        gainDescStart.setText(user.getName()+" wish to ");
        
        //adding tags
        Tags tags = new Tags();
        //TODO : need an api for getting all tags... - Meir
   
        AutoCompleteTextView tagsRow = (AutoCompleteTextView) findViewById(R.id.new_gain_autocomplete_tags);
        ArrayAdapter<String> tagsAdapter = new ArrayAdapter<String>(this, R.layout.list_item, TAGS);//TODO : need to replace TAGS, with tags from server - Meir
        tagsRow.setAdapter(tagsAdapter);
        TextView addedTags = (TextView) findViewById(R.id.new_gain_added_tag);
        
        Button addTagButton = (Button) findViewById(R.id.new_gain_add_tag_button);
        //TODO - need to see how to add tags in a more elegant way.. - Meir
        addTagButton.setOnClickListener(new tagButtonListener(addedTags,tagsRow,getApplicationContext()));
        
        
        final EditText gainDesc = (EditText) findViewById(R.id.add_gain_description);
        Button submitButton = (Button) findViewById(R.id.submit);
        
        //submit section
        submitButton.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
            	Gain newGain = new Gain();
            	//newGain.setCategoryId(categoryId); //TODO : add - Meir
            	
            	String gainDescVal = gainDesc.getText().toString();
            	if(gainDescVal.length()<MIN_DESC_LENGTH){
            		Toast toast = Toast.makeText(AddRequest.this, "Please enter an informative description.", Toast.LENGTH_LONG);
					toast.show();
            		return;
            	}
            	newGain.setDescription(gainDesc.getText().toString());
            	
            	
            	newGain.setToUserId(Registry.GetUser().getId());
            	newGain.setStatus(STATUS.ACTIVE);
            	
            	Log.v("gain desc=",newGain.getDescription());
            	Log.v("gain status=",newGain.getStatus().toString());
            	
            	ArrayList<Tag> tagList = new ArrayList<Tag>();//TODO : for now empty, need to fill it up - meir.
            	
            	Gains gains = new Gains();            
            	ApiResponseObject<Gain> resp = null;
            	try {              
					resp = gains.create(newGain,tagList);
				} catch (JSONException e) { 
					declareInternalError();
					Log.v("create gain","Failed");
					e.printStackTrace(); //TODO - remove in future...
					return;
				} catch (JSONRPCException e) {
					declareInternalError();
					Log.v("create gain","Failed");
					e.printStackTrace(); //TODO - remove in future... 
					return;
				}
				int resCode = resp.getReturnCode(); //TODO - what is the right return code??? - Meir
				
				Log.v("getReturnCode=",Integer.toString(resCode));
				
				if(resCode==0){
					Toast toast = Toast.makeText(AddRequest.this, R.string.gain_added, Toast.LENGTH_LONG);
					toast.show();
				}
				else{
					declareInternalError();
					Log.v("create gain","Failed");
				}
            	
            }
        });
    }
    private String[] transformToStringArray(ArrayList<Category> allCategories) {
    	String[] newStrArr = new String[allCategories.size()];
    	int i=0;
    	for(Category curCategory:allCategories){
    		newStrArr[i]=curCategory.getName();
    		i++;
    	}
		return newStrArr;
	}
	public boolean onCreateOptionsMenu(Menu menu) {
    	Log.v("menu", "inflating menu..");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        
        menu.setGroupVisible(R.id.group1, false);
        menu.setGroupVisible(R.id.group2, false);
        menu.setGroupVisible(R.id.group3, false);
        
        menu.setGroupVisible(R.id.groupNewGain, false);
        
        return true;
    }
	
	public boolean onOptionsItemSelected (MenuItem item){
    	Toast toast;
    	Intent intent;
		 switch (item.getItemId()) {
		    case R.id.menu_profile_button:
		    	intent=new Intent(AddRequest.this,UserPage.class);
		    	AddRequest.this.startActivity(intent);
		        return true;
		    case R.id.help_button:
		    	toast = Toast.makeText(AddRequest.this,"help", Toast.LENGTH_LONG);
				toast.show();
		        return true; 
		    case R.id.menu_search_button:
		    	intent=new Intent(AddRequest.this,GainSearch.class);
		    	AddRequest.this.startActivity(intent);
		        return true;
		    case R.id.menu_home_button:
		    	intent=new Intent(AddRequest.this,Home.class);
		    	AddRequest.this.startActivity(intent);
		        return true;   
		        
		    default:
		        return super.onOptionsItemSelected(item);
		    }
		
    }
    
    private void declareInternalError(){
    	Toast toast = Toast.makeText(AddRequest.this, R.string.internal_error, Toast.LENGTH_LONG);
		toast.show();
		
    }
}